<!--下订单主页面-->
<template>
  <div class="contain">
    <app-header></app-header>
    <div class="form-wrap mb30">
      <!-- <div class="form-choice line" v-if="formDate.list3.length>0">
        <popup-picker class="vux-form-require" title="客户名称" :data="formDate.list3" :columns="3" v-model="formDate.value3" placeholder="点击选择" value-text-align="left" :show-name="formDate.customShow"></popup-picker>
      </div> -->
      <!-- <div class="form-wrap-row" v-if="formDate.list3.length==0">
        <div class="line cf" @click="noneCustoms">
          <div class="label f-l"><span class="red">*</span>客户名称</div>
          <i class="iconfont icon-more f-r"></i>
        </div>
      </div> -->
      <div class="form-wrap-row">
        <div class="line cf" @click="toAddress">
          <div class="label f-l">收货信息</div>
          <i class="iconfont icon-more f-r"></i>
        </div>
      </div>
      <div class="form-wrap-row">
        <p class="ft14 gray mb10">收货人：{{seleAddr.contacts || '--'}}
          <em class="f-r mr20">{{seleAddr.contactsTel}}</em>
        </p>
        <p class="ft14 gray">{{seleAddr.Province | province}}{{seleAddr.City | city}}{{seleAddr.District | district}}{{seleAddr.Address}}</p>
        <div id="address" style="display:none">{{seleAddr.Province | province}}/{{seleAddr.City | city}}/{{seleAddr.District | district}}</div>
      </div>
    </div>
    <div class="place-order-warp mb30">
      <h2 class="tit"><span class="red">*</span>选择下单方式</h2>
      <ul class="cf">
        <li class="place-order-li displayflex" @click="choiceWay(1)" :class="{cur:formDate.choiceGoods}">
          <i class="iconfont icon-drug"></i>
          <dl class="flex1">
            <dt class="ft17">商品下单</dt>
            <dd>自选商品
              <p>提交订单</p>
            </dd>
          </dl>
        </li>
        <li class="place-order-li displayflex" @click="choiceWay(-1)" :class="{cur:formDate.choiceQuick}">
          <i class="iconfont icon-logistics"></i>
          <dl class="flex1">
            <dt class="ft17">快速下单</dt>
            <dd>支持语音、照片、文本三种方式快速下单</dd>
          </dl>
        </li>
      </ul>
    </div>
    <div class="form-wrap mb30" 
         v-if="this.formDate.choiceGoods">
      <div class="form-wrap-row">
        <div class="line displayflex" @click="choicedlist">
          <div class="label">商品清单</div>
          <div class="ipt flex1">已选{{checkItem.length}}种商品</div>
          <i class="iconfont icon-more"></i>
        </div>
      </div>
    </div>
    <div class="form-wrap">
      <div class="form-wrap-row" v-if="this.formDate.choiceGoods">
        <div class="line displayflex">
          <div class="label">总金额</div>
          <div class="ipt flex1 org1">￥{{amount  | fmoney}}</div>
        </div>
      </div>
      <div class="form-wrap-row" v-if="this.formDate.choiceQuick">
        <div class="line displayflex">
          <div class="label">总金额</div> 
          <div class="ipt flex1"><input type="text" placeholder="点击输入" v-model="quickAmount"></div>
          <em class="unit">元</em>
        </div>
      </div>
      <div class="form-choice line">
        <datetime class="vux-form-require" v-model="formDate.arriveTime" :show.sync="visibility" title="要求到货日期" placeholder="点击选择"></datetime>
      </div>
      <!-- <div class="form-choice">
        <popup-picker class="vux-form-require" title="单据类型" :data="billType.list" :columns="3" v-model="billType.value" placeholder="点击选择" value-text-align="left" :show-name="billType.show"></popup-picker>
      </div> -->
    </div>
    <div class="mb30 choice-time" id="setDay">
      <label @change="setTimes(1)">
        <input type="radio" name="time" class="list-radio-check" value="1" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">今天</em>
      </label>
      <label @change="setTimes(2)">
        <input type="radio" name="time" class="list-radio-check" value="2" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">明天</em>
      </label>
      <label @change="setTimes(3)">
        <input type="radio" name="time" class="list-radio-check"value="3" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">后天</em>
      </label>
      <label @change="anotherTime">
        <input type="radio" name="time" class="list-radio-check" value="4" v-model="setday"> 
        <span class="list-radio-circle"></span> 
        <em class="txt">其他</em>
      </label>
    </div>

    <div class="form-wrap mb30">
      <div class="form-wrap-row">
        <div class="line displayflex">
          <div class="label">备注</div>
          <div class="ipt flex1">
            <textarea type="text" placeholder="请输入备注信息（最多200字符）" class="form-txtarea" v-model="memo" maxlength="200"></textarea>
          </div>
        </div>
      </div>
    </div>
    <!-- 单据类型 -->
    <mt-popup
      v-model="popupVisible"
      @click="popupVisible = false;"
      position="right" class="bill-popup">
      <ul class="bill-type">
        <template v-for="item in billType.list">
          <li @click="checkBill(item.value)">{{item.name}}</li>
        </template>
      </ul>
    </mt-popup>

    <div class="form-btn" @click="placeOrder">下单</div>
  </div>
</template>

<script>
import appHeader from '@/components/core/header/app_header.vue';
export default {
  name: "placeOrder",
  components:{
    appHeader
  },
  data() {
    return {
      visibility: false,
      value9: "",
      popupVisible: false,
      formDate: {
        choiceGoods: false,
        choiceQuick: false,
        arriveTime: "",
        list3: [],
        value3: [],
        customShow: true
      },
      seleAddr: "",
      Page: 0,
      Rows: 100,
      checkItem: [],
      amount: 0,
      customid: "",
      billno: "",
      billType: {
        list: [
          {
            value: "04",
            name: "药品"
          },
          {
            value: "01",
            name: "普耗"
          },
          {
            value: "02",
            name: "跟台高值"
          },
          {
            value: "03",
            name: "备货高值"
          },
          {
            value: "05",
            name: "后勤物资"
          },
          {
            value: "06",
            name: "消毒用品"
          },
          {
            value: "07",
            name: "洗涤用品"
          },
          {
            value: "08",
            name: "中药材"
          },
          {
            value: "09",
            name: "设施设备"
          }
        ],
        value: "",
        show: true
      },
      memo: "",
      quickAmount: 0,
      setday: "",
      supp: []
    };
  },
  created() {
    this.getCusdata();
    this.getAddress();
  },
  activated() {
    this.seleAddr = "";
    this.getGoods();
    if (this.formDate.choiceGoods) {
      this.amountNum();
    }
    if (sessionStorage.memo && sessionStorage.memo != "undefined") {
      this.memo = sessionStorage.memo;
    } else {
      this.memo = "";
    }
    // if(this.formDate.value3[0]){
    this.getAddress();
    // }
  },
  watch: {
    "formDate.value3"() {
      this.seleAddr = "";
      this.getAddress();
    }
  },
  methods: {
    anotherTime() {
      this.visibility = true;
    },
    setTimes(val) {
      var curTime = new Date();
      var tomorrow = new Date(curTime.getTime() + 24 * 60 * 60 * 1000);
      var aftertomorrow = new Date(curTime.getTime() + 2 * 24 * 60 * 60 * 1000);
      function fommot(val) {
        var year = val.getFullYear(),
          month = val.getMonth() + 1,
          day = val.getDate();
        if (month < 10) {
          month = "0" + month;
        }
        if (day < 10) {
          day = "0" + day;
        }
        return year + "-" + month + "-" + day;
      }

      if (val == 1) {
        //今天
        this.formDate.arriveTime = fommot(curTime);
      } else if (val == 2) {
        //明天
        this.formDate.arriveTime = fommot(tomorrow);
      } else if (val == 3) {
        //后天
        this.formDate.arriveTime = fommot(aftertomorrow);
      }
    },
    noneCustoms() {
      this.Toast({
        message: "暂无客户，请先添加客户"
      });
      return false;
    },
    //获取是否有选中商品
    getGoods() {
      if (sessionStorage.goods) {
        this.checkItem = JSON.parse(sessionStorage.goods);
      }
    },
    //获取地址
    getAddress() {
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        CCGUID: userinfo.BelongGuid,
        IsChecked: "Y"
      };
      this.Ajax.post("SearchCustomerAddressApi", query).then(function(resp) {
        if (resp.IsSuccess == true) {
          self.addlist = resp.Datas;
          for (var i = 0; i < self.addlist.length; i++) {
            if (self.addlist[i].IsChecked == "Y") {
              self.seleAddr = self.addlist[i];
            }
          }
        }
        if (resp.Datas.length == 0) {
          self.seleAddr = "";
        }
      });
    },
    checkBill(value) {
      this.billType.value = value;
      this.popupVisible = false;
      if (this.formDate.choiceQuick) {
        this.$router.push({
          path: "/order/quick"
        });
      }
      if (this.formDate.choiceGoods) {
        this.$router.push({
          path: "/order/placeChoice",
          query: {
            MedGuid: this.customid,
            billtype: value
          }
        });
      }
    },
    //选择下单方式
    choiceWay(way) {
      //   this.customid = this.formDate.value3[0];
      //   if(!this.customid || this.customid.length==0){
      //     this.Toast({
      //       message:'请选择客户名称'
      //     })
      //     return false;
      //   }
       sessionStorage.clear();
      if (way > 0) {
        this.formDate.choiceQuick = false;
        this.formDate.choiceGoods = true;
      } else {
        this.formDate.choiceQuick = true;
        this.formDate.choiceGoods = false;
      }
      this.popupVisible = true;
    },
    //商品清单跳转
    choicedlist() {
      this.$router.push({
        path: "/order/placeChoiced"
      });
    },
    //收货地址跳转
    toAddress() {
      //   this.customid = this.formDate.value3[0];
      //   if(!this.customid || this.customid.length==0){
      //     this.Toast({
      //       message:'请选择客户名称'
      //     })
      //     return false;
      //   }
      var userinfo = JSON.parse(localStorage.userinfo);
      this.$router.push({
        path: "/order/address",
        query: { id: userinfo.BelongGuid }
      });
    },
    //获取供应关系业务员列表
    getCusdata() {
      var self = this;
      var userinfo = JSON.parse(localStorage.userinfo);
      var query = {
        MedGuid: userinfo.BelongGuid,
        TenantGuid: userinfo.TenantGUID,
        CorpGuid: userinfo.CorpGuid
      };
      this.Ajax.post("SearchMfsupplyrelation", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.supp = resp.Data;
        }
      });
    },
    //总金额
    amountNum() {
      this.amount = 0;
      for (var i = 0; i < this.checkItem.length; i++) {
        var price = this.checkItem[i].Price || 0;
        var qty = this.checkItem[i].PurchaserPoQty || 0;
        this.amount += price * parseInt(qty);
      }
    },
    //获取订单号
    creatBill() {
      var date = new Date();
      var Num = "";
      for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
      }
      var month, curdate;
      if (date.getMonth() + 1 < 9) {
        month = "0" + (date.getMonth() + 1);
      } else {
        month = date.getMonth() + 1;
      }
      if (date.getDate() < 9) {
        curdate = "0" + date.getDate();
      } else {
        curdate = date.getDate();
      }
      this.billno = "DD" + date.getFullYear() + month + curdate + "0001" + Num;
    },
    //检验必填项
    checkForm() {
      if (!this.formDate.choiceQuick && !this.formDate.choiceGoods) {
        this.Toast({
          message: "请选择下单方式"
        });
        return false;
      }
      if (this.checkItem.length == 0 && this.formDate.choiceGoods) {
        this.Toast({
          message: "请选择商品"
        });
        return false;
      }
      if (this.formDate.choiceQuick) {
        var imglist = sessionStorage.imglist,
          voicelist = sessionStorage.voicelist;
        if (!imglist && !voicelist && !this.memo) {
          this.Toast({
            message: "请提交语音或者照片或者文本"
          });
          return false;
        }
      }
      if (!this.formDate.arriveTime) {
        this.Toast({
          message: "请选择要求到货日期"
        });
        return false;
      }
      if (!this.billType.value) {
        this.Toast({
          message: "请选择单据类型"
        });
        return false;
      }
      return true;
    },
    //reset数据
    resetDate() {
      //提交订单就把选中商品的缓存清空
      this.formDate.arriveTime = "";
      this.formDate.choiceGoods = false;
      this.formDate.choiceQuick = false;
      this.formDate.value3 = [];
      sessionStorage.clear();
      this.getCusdata();
      this.billType.value = "";
      this.setday = "";
      this.memo = "";
      this.amount = 0;
      this.seleAddr = [];
      this.quickAmount = 0;
    },
    //点击提交
    placeOrder() {
      if (!this.checkForm()) {
        return false;
      }
      var self = this;
      var info = JSON.parse(localStorage.userinfo);
      this.creatBill();
      var query = {
        BillNo: this.billno,
        TenantGuid: info.TenantGUID,
        CorpGuid: info.CorpGuid,
        MedName: info.BelongName,
        BillType: this.billType.value,
        SupplierName: info.CorpName,
        MedGuid: info.BelongGuid,
        MedDeptName: "", //要货科室
        MedStoreName: "", //要货库房
        PlanEndDate: this.formDate.arriveTime,
        Province: this.seleAddr.Province,
        City: this.seleAddr.City,
        District: this.seleAddr.District,
        CountSum: this.formDate.choiceQuick ? 0 : this.checkItem.length,
        Address: this.seleAddr.Address,
        BuyerGUID: self.supp.CreateUserID,
        BuyerName: self.supp.CreateUserName,
        CreateUserId: info.StaffID,
        UpdateUserId: info.StaffID,
        UpdateUserName: info.Name,
        CreateUserName: info.Name,
        Venue: $("#address").html(),
        Memo: this.memo
      };
      if (this.formDate.choiceQuick) {
        query.imglist = sessionStorage.imglist
          ? JSON.parse(sessionStorage.imglist)
          : "";
        query.Voice = sessionStorage.voicelist;
        query.DetailSum = this.quickAmount; //总金额
      } else {
        query.imglist = null;
        query.Voice = null;
        query.orderdeail = this.checkItem;
        query.DetailSum = this.amount; //总金额
      }
      this.Ajax.post("Overbooking", query).then(function(resp) {
        if (resp.IsSuccess) {
          self.resetDate();
          self.MessageBox.alert("下单成功").then(action => {
            self.$router.push({
              path: "/order"
            });
          });
        } else {
          self.Toast({
            message: resp.ErrorMessage || "操作失败"
          });
        }
      });
    }
  }
};
</script>